package com.sun.servlet;

import com.sun.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Author Sun
 * @Date 2020/4/20 23:02
 * @Version 1.0
 */
public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //通过request获取session对象
        HttpSession session = req.getSession();
        /*
            在创建session对象的时候，cookie做了两件事：
            Cookie cookie = new Cookie("JSESSIONID", sessionId);
            resp.addCookie(cookie);
         */

        //存数据，相较于cookie，session的value是object类型，可以存更多类型的数据
        session.setAttribute("person", new Person("黎明",20));

        //获取session的ID
        String sessionId = session.getId();

        //判断session是不是新建
        if(session.isNew()){
            resp.getWriter().write("session创建成功："+sessionId);
        }else {
            resp.getWriter().write("session在服务器中已存在："+sessionId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
